export default class {
  constructor(selector = document){
      this.selector = selector;
      this.update();
      this.lazy();
      var srollTarget = this.selector === document ? window : this.selector;
      srollTarget.addEventListener('scroll',()=>{
           //懒加载
           this.lazy();
      },false)
  }

  update(){
      this.list = this.selector.querySelectorAll('img[data-src]');
      this.lazy();
  }

  lazy(){
      let len = this.list.length;
      if(len ==0) return false;
      for(let i = 0;i<len;i++){
          let img = this.list[i];
          let attr = img.getAttribute('lazy');
          if(attr !== 'done' && attr !== 'loading'){
              //do login
              let rect = img.getBoundingClientRect();
              let winH = window.innerHeight;
              if(rect.top > -20 && rect.top < winH + 20){
                  this.load(img);
              }
          }
      }
  }

  load(img){
      let image = new Image;
      let src = img.getAttribute('data-src');
      let thumb = img.getAttribute('thumb') || '';
      let error = img.getAttribute('error');
      img.setAttribute('lazy','loading');

      if(thumb) img.setAttribute('src',thumb);

      image.onload = function(){
          img.setAttribute('src',src);
          img.setAttribute('lazy','done');
      }

      image.onerror = function(e){
        img.setAttribute('lazy','error');
        if(error){
          img.setAttribute('src',error);
        }
      }
      image.src = src;
  }
}
